package cn.ac.aircas.framework.web.service;

import cn.ac.aircas.common.utils.*;
import cn.ac.aircas.system.service.ISysConfigService;
import cn.ac.aircas.system.service.ISysRoleService;
import org.springframework.stereotype.Service;
import cn.ac.aircas.common.constant.Constants;
import cn.ac.aircas.common.core.domain.entity.SysUser;
import cn.ac.aircas.common.core.domain.model.LoginUser;
import cn.ac.aircas.common.exception.ServiceException;
import cn.ac.aircas.common.exception.user.UserPasswordNotMatchException;
import cn.ac.aircas.common.utils.ip.IpUtils;
import cn.ac.aircas.framework.manager.AsyncManager;
import cn.ac.aircas.framework.manager.factory.AsyncFactory;
import cn.ac.aircas.framework.security.context.AuthenticationContextHolder;
import cn.ac.aircas.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Optional;

/**
 * @projectName: RuoYi-Vue
 * @package: cn.ac.aircas.framework.web.service
 * @className: ThirdLoginService
 * @author: sean
 * @description: TODO
 * @date: 2023/2/22 7:53
 * @version: 1.0
 */
@Service
public class ThirdLoginService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysConfigService configService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private ThirdUserDetailsService userDetailsService;

    /**
     * 无密码登录
     *
     * @param userName
     * @return
     * @author sean
     * @date 2023/2/21 17:52
     */
    public String noPwdLogin(String userName) {
        LoginUser loginUser
                = (LoginUser) userDetailsService.loadUserByUsername(userName);
        // 记录登陆信息
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGIN_SUCCESS,
                MessageUtils.message("user.login.success")));
        recordLoginInfo(loginUser.getUserId());
        return tokenService.createToken(loginUser);
    }

    /**
     * 不加验证码登录
     *
     * @param username 用户名
     * @param password 密码
     * @param uuid     唯一标识
     * @return 结果
     * @author sean
     * @date 2023/2/21 17:52
     */
    public String loginNoCode(String username, String password, String uuid) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser =
                (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * @param token:
     * @return String
     * @title thirdLogin
     * @descriptions 三方平台登陆
     * @author sean
     * @date 2023/2/21 17:52
     */
    public String thirdLogin(String token) {
        // 根据token获取用户相关信息, 需要接入第三方平台获取
        // SysUser sysUser = userService.getUserByToken(token);
        SysUser sysUser = new SysUser();
        if (userService.checkUserNameUnique(sysUser)) {
            // 数据库未存在，进行注册
        } else {
            // 数据库存在，进行update并登陆
        }

        List<Long> ids = new ArrayList<>();
        ids.add(Long.parseLong(configService.selectConfigByKey("sys.user.initRoleId")));
        sysUser.setRoleIds(ids.toArray(new Long[0]));
        sysUser.setUserName(token);
        sysUser.setNickName(token);
        sysUser.setCreateBy("OAuth2");
        sysUser.setDeptId(Long.parseLong(configService.selectConfigByKey("sys.user.initDeptId")));
        ids.clear();
        ids.add(Long.parseLong(configService.selectConfigByKey("sys.user.initPostId")));
        sysUser.setPostIds(ids.toArray(new Long[0]));
        sysUser.setPassword(SecurityUtils.encryptPassword(configService.selectConfigByKey("sys.user.initPassword")));
        this.addOrUpdateUser(sysUser);
        return this.noPwdLogin(sysUser.getUserName());
    }


    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public void addOrUpdateUser(SysUser sysUser) {
        if (userService.checkUserNameUnique(sysUser)) {
            userService.insertUser(sysUser);
        }
    }
}

